using System;
using Fornax020.SerialComm.Protocol;

namespace Fornax020.SerialComm.Parsing
{
    /// <summary>
    /// 串口响应解析器 - 策略模式的具体实现
    /// 单一职责原则：专门负责串口数据的解析
    /// </summary>
    public class ResponseParser : IDataParser
    {
        #region 私有字段
        private readonly IDataValidator _validator;
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="validator">数据验证器</param>
        public ResponseParser(IDataValidator validator = null)
        {
            _validator = validator ?? ValidatorFactory.CreateXRayValidator();
        }
        #endregion

        /// <summary>
        /// 解析X射线设备的数据
        /// 策略模式：实现具体的数据解析算法
        /// </summary>
        /// <param name="dataString">原始数据字符串</param>
        /// <returns>解析结果</returns>
        public ResponseData Parse(string dataString)
        {
            var result = new ResponseData();
            System.Diagnostics.Debug.WriteLine($"[ResponseParser] 开始解析数据: '{dataString}' (长度: {dataString.Length})");

            try
            {
                // 首先验证数据格式
                var validationResult = _validator.Validate(dataString);
                System.Diagnostics.Debug.WriteLine($"[ResponseParser] 数据验证结果: IsValid={validationResult.IsValid}, Message={validationResult.ErrorMessage}");
                if (!validationResult.IsValid)
                {
                    result.IsValid = false;
                    return result;
                }

                // 根据数据长度和格式进行解析
                if (dataString.Length >= 2)
                {
                    string commandType = dataString.Substring(1, 2);

                    switch (commandType)
                    {
                        case ProtocolConstants.CommandTypes.KV_FEEDBACK:
                            ParseKvFeedback(dataString, result);
                            break;
                        case ProtocolConstants.CommandTypes.MA_FEEDBACK:
                            ParseMaFeedback(dataString, result);
                            break;
                        case ProtocolConstants.CommandTypes.FIL_FEEDBACK:
                            ParseFilFeedback(dataString, result);
                            break;
                        case ProtocolConstants.CommandTypes.MONITOR_DATA:
                            ParseMonitorData(dataString, result);
                            break;
                        case ProtocolConstants.CommandTypes.FIRMWARE_VERSION:
                            ParseFirmwareVersion(dataString, result);
                            break;
                        case ProtocolConstants.CommandTypes.ERROR_INFO:
                            ParseErrorInfo(dataString, result);
                            break;
                        case ProtocolConstants.CommandTypes.START_EXPOSURE_RESPONSE:
                            ParseStartExposureResponse(dataString, result);
                            break;
                        case ProtocolConstants.CommandTypes.STOP_EXPOSURE_RESPONSE:
                            ParseStopExposureResponse(dataString, result);
                            break;
                        case ProtocolConstants.CommandTypes.CLEAR_ERROR_RESPONSE:
                            ParseClearErrorResponse(dataString, result);
                            break;
                        default:
                            // 尝试解析为默认格式
                            ParseDefaultFormat(dataString, result);
                            break;
                    }
                }
                else
                {
                    result.IsValid = false;
                }
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                // 可以记录日志
            }

            return result;
        }

        #region 私有解析方法
        /// <summary>
        /// 解析KV反馈数据
        /// </summary>
        private void ParseKvFeedback(string data, ResponseData result)
        {
            if (data.Length >= ProtocolConstants.PacketLength.KV_FEEDBACK)
            {
                string kvString = data.Substring(3, 4);
                if (double.TryParse(kvString, out double kvValue))
                {
                    result.CommandType = ProtocolConstants.CommandTypes.KV_FEEDBACK;
                    result.KvValue = kvValue / 10.0; // 转换为实际值
                    result.IsValid = true;
                }
            }
        }

        /// <summary>
        /// 解析MA反馈数据
        /// </summary>
        private void ParseMaFeedback(string data, ResponseData result)
        {
            if (data.Length >= ProtocolConstants.PacketLength.MA_FEEDBACK)
            {
                string maString = data.Substring(3, 4);
                if (double.TryParse(maString, out double maValue))
                {
                    result.CommandType = ProtocolConstants.CommandTypes.MA_FEEDBACK;
                    result.MaValue = maValue;
                    result.IsValid = true;
                }
            }
        }

        /// <summary>
        /// 解析FIL反馈数据
        /// </summary>
        private void ParseFilFeedback(string data, ResponseData result)
        {
            if (data.Length >= ProtocolConstants.PacketLength.FIL_FEEDBACK)
            {
                string filString = data.Substring(3, 4);
                if (double.TryParse(filString, out double filValue))
                {
                    result.CommandType = ProtocolConstants.CommandTypes.FIL_FEEDBACK;
                    result.FilValue = filValue;
                    result.IsValid = true;
                }
            }
        }

        /// <summary>
        /// 解析监控数据
        /// </summary>
        private void ParseMonitorData(string data, ResponseData result)
        {
            System.Diagnostics.Debug.WriteLine($"[ResponseParser] 开始解析MO数据: '{data}' (长度: {data.Length})");
            
            if (data.Length >= ProtocolConstants.PacketLength.MONITOR_DATA)
            {
                result.CommandType = ProtocolConstants.CommandTypes.MONITOR_DATA;
                result.MonitorData = data;
                
                // 解析MO指令响应数据
                // 格式: STX + 'M' + 'O' + SP + KV(4位) + SP + MA(4位) + SP + FIL(4位) + CR
                try
                {
                    // 检查数据格式是否正确
                    if (data.Length >= 18 && data[0] == ProtocolConstants.STX && data[1] == 'M' && data[2] == 'O')
                    {
                        System.Diagnostics.Debug.WriteLine($"[ResponseParser] MO数据格式正确，开始解析");
                        
                        // 解析KV值 (位置4-7)
                        string kvString = data.Substring(4, 4);
                        if (int.TryParse(kvString, out int kvRaw))
                        {
                            result.KvValue = kvRaw / 10.0; // KV值需要除以10转换为实际值
                            System.Diagnostics.Debug.WriteLine($"[ResponseParser] KV解析: '{kvString}' -> {kvRaw} -> {result.KvValue}");
                        }
                        
                        // 解析MA值 (位置9-12)
                        string maString = data.Substring(9, 4);
                        if (int.TryParse(maString, out int maRaw))
                        {
                            result.MaValue = maRaw; // MA值直接使用
                            System.Diagnostics.Debug.WriteLine($"[ResponseParser] MA解析: '{maString}' -> {maRaw}");
                        }
                        
                        // 解析FIL值 (位置14-17)
                        string filString = data.Substring(14, 4);
                        if (int.TryParse(filString, out int filRaw))
                        {
                            result.FilValue = filRaw; // FIL值直接使用
                            System.Diagnostics.Debug.WriteLine($"[ResponseParser] FIL解析: '{filString}' -> {filRaw}");
                        }
                        
                        result.IsValid = true;
                        System.Diagnostics.Debug.WriteLine($"[ResponseParser] MO解析完成: KV={result.KvValue}, MA={result.MaValue}, FIL={result.FilValue}, IsValid={result.IsValid}");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"[ResponseParser] MO数据格式不正确，尝试空格分割解析");
                        // 如果格式不正确，尝试使用空格分割的方式解析
                        string[] parts = data.Split(ProtocolConstants.SP);
                        if (parts.Length >= 4)
                        {
                            if (double.TryParse(parts[1], out double kvValue))
                                result.KvValue = kvValue / 10.0;
                            if (double.TryParse(parts[2], out double maValue))
                                result.MaValue = maValue;
                            if (double.TryParse(parts[3], out double filValue))
                                result.FilValue = filValue;
                        }
                        result.IsValid = true;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"[ResponseParser] MO解析异常: {ex.Message}");
                    // 解析失败时使用原始数据
                    result.IsValid = false;
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"[ResponseParser] MO数据长度不足: {data.Length} < {ProtocolConstants.PacketLength.MONITOR_DATA}");
            }
        }

        /// <summary>
        /// 解析固件版本
        /// </summary>
        private void ParseFirmwareVersion(string data, ResponseData result)
        {
            if (data.Length >= ProtocolConstants.PacketLength.FIRMWARE_VERSION)
            {
                result.CommandType = ProtocolConstants.CommandTypes.FIRMWARE_VERSION;
                result.FirmwareVersion = data.Substring(3, data.Length - 4); // 去掉STX和CR
                result.IsValid = true;
            }
        }

        /// <summary>
        /// 解析错误信息
        /// </summary>
        private void ParseErrorInfo(string data, ResponseData result)
        {
            if (data.Length >= ProtocolConstants.PacketLength.ERROR_INFO)
            {
                result.CommandType = ProtocolConstants.CommandTypes.ERROR_INFO;
                result.ErrorCode = data.Substring(3, 3);
                result.IsValid = true;
            }
        }

        /// <summary>
        /// 解析开始曝光响应
        /// </summary>
        private void ParseStartExposureResponse(string data, ResponseData result)
        {
            if (data.Length >= ProtocolConstants.PacketLength.START_EXPOSURE_RESPONSE)
            {
                result.CommandType = ProtocolConstants.CommandTypes.START_EXPOSURE_RESPONSE;
                result.IsValid = true;
            }
        }

        /// <summary>
        /// 解析停止曝光响应
        /// </summary>
        private void ParseStopExposureResponse(string data, ResponseData result)
        {
            if (data.Length >= ProtocolConstants.PacketLength.STOP_EXPOSURE_RESPONSE)
            {
                result.CommandType = ProtocolConstants.CommandTypes.STOP_EXPOSURE_RESPONSE;
                result.IsValid = true;
            }
        }

        /// <summary>
        /// 解析清除错误响应
        /// </summary>
        private void ParseClearErrorResponse(string data, ResponseData result)
        {
            if (data.Length >= ProtocolConstants.PacketLength.CLEAR_ERROR_RESPONSE)
            {
                result.CommandType = ProtocolConstants.CommandTypes.CLEAR_ERROR_RESPONSE;
                result.IsValid = true;
            }
        }

        /// <summary>
        /// 解析默认格式数据
        /// </summary>
        private void ParseDefaultFormat(string data, ResponseData result)
        {
            // 尝试解析为无STX格式
            if (data.StartsWith("VP") && data.Length >= 6)
            {
                ParseKvFeedback(ProtocolConstants.STX + data, result);
            }
            else if (data.StartsWith("CP") && data.Length >= 6)
            {
                ParseMaFeedback(ProtocolConstants.STX + data, result);
            }
            else if (data.StartsWith("MO") && data.Length >= 18)
            {
                ParseMonitorData(ProtocolConstants.STX + data, result);
            }
            else if (data.StartsWith("EN1") && data.Length >= 4)
            {
                ParseStartExposureResponse(ProtocolConstants.STX + data, result);
            }
            else if (data.StartsWith("EN0") && data.Length >= 4)
            {
                ParseStopExposureResponse(ProtocolConstants.STX + data, result);
            }
            else if (data.StartsWith("CL") && data.Length >= 3)
            {
                ParseClearErrorResponse(ProtocolConstants.STX + data, result);
            }
            else
            {
                result.IsValid = false;
            }
        }
        #endregion
    }
}
